package com.guigu.controller;

import com.guigu.exception.CustomException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {

    /**
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        ModelAndView modelAndView = new ModelAndView();

        String header = request.getHeader("X-requested-with");
        if(header != null && header.equalsIgnoreCase("XMLHttpRequest")){

            //响应给客户端的数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("errMsg", ex.getMessage());
            map.put("errCode", "1");

            //MappingJackson2JsonView实现了view接口，能作为一个视图响应给客户端，同时还能存储json数据
            MappingJackson2JsonView view = new MappingJackson2JsonView();
            view.setAttributesMap(map);
            modelAndView.setView(view);
        }else {
            if(ex instanceof CustomException == false){
                modelAndView.setViewName("jsp/error");
            }else {
                modelAndView.setViewName("jsp/error");
            }
            modelAndView.addObject("errMsg",ex.getMessage());
        }
        return modelAndView;
    }
}
